/**
 * 聊天API接口
 */
import axios from 'axios'

// 使用相对路径，通过Vite代理访问后端，避免CORS问题
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '/api/v1'

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true, // 支持跨域携带cookie
})

// 请求拦截器 - 添加认证token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response?.status === 401) {
      // Token过期，清除并跳转登录
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export interface ChatRequest {
  message: string
  use_rag?: boolean
  stream?: boolean
}

export interface ChatResponse {
  success: boolean
  reply: string
  used_rag: boolean
  retrieved_docs: any[]
  tokens?: {
    prompt: number
    completion: number
    total: number
  }
  cost?: number
  duration?: number
}

/**
 * 发送聊天消息
 */
export const sendMessage = (data: ChatRequest): Promise<ChatResponse> => {
  return api.post('/chat/chat', data)
}

/**
 * 获取欢迎语
 */
export const getGreeting = (): Promise<{ success: boolean; greeting: string }> => {
  return api.get('/chat/greeting')
}

/**
 * 获取对话历史
 */
export const getHistory = (limit: number = 20): Promise<any> => {
  return api.get('/chat/history', { params: { limit } })
}

/**
 * 清除对话历史
 */
export const clearHistory = (): Promise<{ success: boolean; message: string }> => {
  return api.delete('/chat/history')
}

export default api

